//
//  MessageDao.m
//  JiaoX
//
//  Created by yinqy on 15/3/11.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "ChatMsgDao.h"
#import "FMDB.h"
#import "Conversation.h"
#import "UserInfoDao.h"

#define MSG_TABLENAME @"TB_CHAT_MESSAGES"
#define SESSION_TABLENAME @"TB_CHAT_SESSIONS"


@interface ChatMsgDao()
{
    FMDatabase *db;
    NSString *database_path;
}

@end

@implementation ChatMsgDao
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [paths objectAtIndex:0];
        database_path = [documents stringByAppendingPathComponent:DB_NAME];
        db = [FMDatabase databaseWithPath:database_path];
        [db open];
        [self createTable];
    }
    return self;
}

/**
 *  创建表
 */
- (void)createTable{

    if (![db tableExists:MSG_TABLENAME]) {
        /**
         * messageId 消息的唯一id,不能为null
         * ownerId 用户自己的id不能为null
         * fromPeerId 发送方的id ,不能为null
         * convId 会话id,不能为null
         * toPeerId 接收方的id
         * content 聊天内容
         * status 消息状态，发送成功、失败等
         * msgType 消息类型，文本、图片、声音
         * roomType 聊天类型，单聊还是群聊
         * groupId 群的id 如果这个不为空，那么代表是群消息。toPeerId为空
         * readStatus 消息是否查看，已读、未读
         * timestamp 时间轴
         */
        NSString *sql =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (_id integer primary key autoincrement, messageId varchar(63) unique not null,ownerId varchar(255) not null, fromPeerId varchar(255) not null, toPeerId varchar(255),convId varchar(255), content varchar(1023),status integer, msgType integer, roomType integer,groupId varchar(255), readStatus integer,timestamp integer)",MSG_TABLENAME];
        [db executeUpdate:sql];
    }
    
    
    if (![db tableExists:SESSION_TABLENAME]) {
        /**
         * type session类型，群聊或者单聊
         * otherId 对方的id，群id或者对方的id
         * ownerId 用户自己的id不能为null
         */
        NSString *sql =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (_id integer primary key autoincrement,type integer,otherId varchar(255),ownerId varchar(255) not null)",SESSION_TABLENAME];
        [db executeUpdate:sql];
    }
}


-(void)insertMessage:(JXMessage *)message{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:message.messageId forKey:@"messageId"];
    [dict setObject:CURRENTUSERID forKey:@"ownerId"];
    [dict setObject:message.fromPeerId forKey:@"fromPeerId"];
    [dict setObject:message.toPeerId forKey:@"toPeerId"];
    [dict setObject:message.conversionId forKey:@"convId"];
    [dict setObject:message.payload forKey:@"content"];
    if (![Utils isBlankString:message.groupId]) {
        [dict setObject:message.groupId forKey:@"groupId"];
    }else{
        [dict setObject:@"" forKey:@"groupId"];
    }
    [dict setObject:[NSNumber numberWithInt:message.msgType] forKey:@"msgType"];
    [dict setObject:[NSNumber numberWithInt:message.roomType] forKey:@"roomType"];
    [dict setObject:[NSNumber numberWithInt:message.readStatus] forKey:@"readStatus"];
    [dict setObject:[NSNumber numberWithInt:message.sendStatus] forKey:@"status"];
    [dict setObject:[NSNumber numberWithLongLong:message.timestamp] forKey:@"timestamp"];
    
    BOOL res = [db executeUpdate:@"insert into \"TB_CHAT_MESSAGES\" (\"messageId\", \"ownerId\", \"fromPeerId\", \"toPeerId\",\"convId\", \"content\", \"msgType\", \"roomType\",\"groupId\", \"readStatus\",\"status\", \"timestamp\") values (:messageId, :ownerId, :fromPeerId, :toPeerId, :convId, :content, :msgType, :roomType, :groupId, :readStatus, :status, :timestamp)" withParameterDictionary:dict];
    if (!res) {
        JXLog(@"insert msg error");
    } else {
        JXLog(@"insert msg success");
    }
}

/**
 *  获取聊天记录。
 *
 *  @param userId    用户id娇羞的程序员
 *  @param timestamp 时间，如果为空获取最后20条。如果不为空，获取这个时间之前的20条
 *  @param number 查询条数
 *
 *  @return
 */
-(NSArray *)getMsgsWithUserId:(NSString *)userId timestamp:(NSString *)timestamp number:(NSInteger)number{
    NSMutableArray *array = [NSMutableArray array];
    
    NSString *tmiesTampStr = @"";
    if (![Utils isBlankString:timestamp]) {//如果timestamp有值，则加上这个条件
        tmiesTampStr = [NSString stringWithFormat:@"and timestamp <%@",timestamp];
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE ((fromPeerId=%@ and toPeerId =%@) or (fromPeerId=%@ and toPeerId = %@)) and ownerId = %@ %@ ORDER BY timestamp DESC LIMIT %ld",MSG_TABLENAME,CURRENTUSERID,userId,userId,CURRENTUSERID,CURRENTUSERID,tmiesTampStr,(long)number];
    FMResultSet *set = [db executeQuery:sql];
    while ([set next]) {
        [array insertObject:[JXMessage fromFMResultSet:set] atIndex:0];
        //SELECT * FROM TB_CHAT_MESSAGES WHERE ((fromPeerId=8 and toPeerId =50533) or (fromPeerId=50533 and toPeerId = 8)) and ownerId = 8  ORDER BY timestamp DESC LIMIT 20
    }
    return array;
}


-(BOOL)setMessageReadStatus:(NSString *)userId{
    NSString *sql = [NSString stringWithFormat:@"update %@ set readStatus = 1 where (fromPeerId = %@ and toPeerId = %@ ) or (fromPeerId = %@ and toPeerId = %@) and ownerId = %@",MSG_TABLENAME, CURRENTUSERID,userId,userId,CURRENTUSERID,CURRENTUSERID];
    BOOL result = [db executeUpdate:sql];
    JXLog(@"更改消息是否已读的状态：result=%@",[NSNumber numberWithBool:result]);
    return result;
}

-(BOOL)setMessageSendStatus:(NSString *)objectId sendStatus:(SendStatus)sendStatus{
    NSString *sql = [NSString stringWithFormat:@"update %@ set status = %ld where messageId = '%@'",MSG_TABLENAME,(long)[[NSNumber numberWithInt:sendStatus] integerValue],objectId];
    BOOL result = [db executeUpdate:sql];
    JXLog(@"更改消息发送状态：result=%@",[NSNumber numberWithBool:result]);
    return result;
}

-(BOOL)setMessageContent:(NSString *)messageId content:(NSString *)content{
    NSString *sql = [NSString stringWithFormat:@"update %@ set content = '%@' where messageId = '%@'",MSG_TABLENAME,content,messageId];
    BOOL result = [db executeUpdate:sql];
    JXLog(@"更改消息内容：result=%@",[NSNumber numberWithBool:result]);
    return result;
}


-(BOOL)addSessionWithId:(NSString *)ID type:(RoomType)type{
    FMResultSet *set = [db executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ WHERE ownerId = %@ AND otherId = %@ AND type = %ld",SESSION_TABLENAME,CURRENTUSERID,ID,(long)[[NSNumber numberWithInt:type] integerValue]]];
    if (![set next]) {
        //添加一条
        return [db executeUpdate:[NSString stringWithFormat:@"INSERT INTO %@ (type,otherId,ownerId) values (%ld,%@,%@)",SESSION_TABLENAME,(long)[[NSNumber numberWithInt:type] integerValue],ID,CURRENTUSERID]];
    }
    return YES;
}


-(BOOL)deleteSessionWithId:(NSString *)ID type:(RoomType)type{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE otherId = %@ AND type = %d",SESSION_TABLENAME,ID,[NSNumber numberWithInt:type].intValue];
    return [db executeUpdate:sql];
}

-(BOOL)deleteMessageWithOtherId:(NSString *)ID{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE ((fromPeerId=%@ and toPeerId =%@) or (fromPeerId=%@ and toPeerId = %@)) and ownerId = %@",MSG_TABLENAME,ID,CURRENTUSERID,CURRENTUSERID,ID,CURRENTUSERID];
    return [db executeUpdate:sql];
}

///**
// * 根据会话id 查询聊天记录
// *
// * @param convId   会话id
// * @param numberBy 查询的条数
// * @return Msg的集合
// */
//
//-(NSArray *)getMsgsWithConvId:(NSString *)ConvId numberBy:(int)numberBy pageNumber:(int)pageNumber{
//    if ([db open]) {
//        NSMutableArray *msgs = [NSMutableArray new];
//        NSString *sql= [NSString stringWithFormat:
//                        @"SELECT * FROM '%@' where convId = '%@' ORDER BY timestamp DESC LIMIT %d OFFSET %d",
//                        TABLENAME,ConvId,pageNumber,numberBy];
//        BOOL res = [db executeUpdate:sql];
//        if (!res) {
//            JXLog(@"error when select db table");
//        } else {
//            JXLog(@"success to select db table");
//        }
//        [db close];
//        return msgs;
//    }
//    return nil;
//}


-(NSArray *)getConversionsWithOwnerId:(NSString *)ownerId{
    NSMutableArray *conversations = [NSMutableArray new];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE ownerId = %@ AND type = %ld",SESSION_TABLENAME,CURRENTUSERID,(long)[[NSNumber numberWithInt:RoomTypeSingle] integerValue]];
    JXLog(@"sql=%@",sql);
    FMResultSet * rs = [db executeQuery:sql];
    while([rs next]) {
        Conversation *conversation = [Conversation new];
        
        NSString *otherId = [rs stringForColumn:@"otherId"];
        
        //得到最后一条消息。
        sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE ((fromPeerId=%@ and toPeerId =%@) or (fromPeerId=%@ and toPeerId = %@)) and ownerId = %@ ORDER BY timestamp DESC LIMIT %d",MSG_TABLENAME,CURRENTUSERID,otherId,otherId,CURRENTUSERID,CURRENTUSERID,1];
        FMResultSet *set = [db executeQuery:sql];
        JXMessage *message = nil;
        if ([set next]) {
            message = [JXMessage fromFMResultSet:set];
        }else{
            continue;
        }
        [conversation setMsg:message];
        
        //得到未读消息数
        int count = 0;
        NSString *childSql1 = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE ((fromPeerId=%@ and toPeerId =%@) or (fromPeerId=%@ and toPeerId = %@)) AND ownerId = %@ AND readStatus = '%ld'",MSG_TABLENAME,CURRENTUSERID,otherId,otherId,CURRENTUSERID,CURRENTUSERID,(long)ReadStatusUnread];
        FMResultSet * childRs = [db executeQuery:childSql1];
        if ([childRs next]) {
            count = [childRs intForColumnIndex:0];
        }
        [conversation setUnreadCount:count];
        
        //得到聊天对象信息
        NSString *childSql2 = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userId = '%@'",@"TB_USER_INFO",otherId];
        FMResultSet *childRs2 = [db executeQuery:childSql2];
        JXLog(@"childSql2=%@",childSql2);
        UserInfo *userInfo = nil;
        if ([childRs2 next]) {
            NSData *userInfoData = [childRs2 objectForColumnName:@"userInfo"];
            NSDictionary *userInfoDic = [NSKeyedUnarchiver unarchiveObjectWithData:userInfoData];
            JXLog(@"userInfoDic = %@",userInfoDic);
            userInfo = [UserInfo objectWithKeyValues:userInfoDic];
            
        }else{
            continue;
        }
        [conversation setToUser:userInfo];
        [conversations addObject:conversation];
    }
    return conversations;
}


-(NSInteger)getAllUnReadMsgCount{
    if (!TOKEN) {
        return 0;
    }
    int count = 0;
    NSString *childSql1 = [NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE ownerId = %@ AND readStatus = '%ld'",MSG_TABLENAME,CURRENTUSERID,(long)ReadStatusUnread];
    FMResultSet * childRs = [db executeQuery:childSql1];
    if ([childRs next]) {
        count = [childRs intForColumnIndex:0];
    }
    return count;
}

-(void)dealloc{
    [db close];
}

@end
